<template>
	<el-dialog v-model="dialogFormVisible" width="450px" class="register-css">
		<el-page-header @back="goBack">
			<template #content>
				<span class="text-large font-800 mr-3">新用户注册</span>
			</template>
		</el-page-header>
		<div class="login-containers">
			<el-form ref="userRef" :model="user" class="login-forms" label-width="10px">
				<el-form-item prop="user_name">
					<el-input v-model="user.user_name" placeholder="账号" clearable @blur="checkUsername()" />
					<el-text class="mx-1" size="small" type="danger">{{userTip.yhmTip}}</el-text>
				</el-form-item>

				<el-form-item prop="pwd">
					<el-input v-model="user.pwd" type="password" placeholder="密码" clearable @blur="checkPwd()" />
					<el-text class="mx-1" size="small" type="danger">{{userTip.pwdTip}}</el-text>
				</el-form-item>
				<el-form-item prop="pwd2">
					<el-input v-model="user.pwd2" type="password" placeholder="确认密码" clearable @blur="checkPwd2()" />
					<el-text class="mx-1" size="small" type="danger">{{userTip.pwd2Tip}}</el-text>
				</el-form-item>
				<el-form-item prop="user_sjh">
					<el-input v-model="user.user_sjh" placeholder="手机号(选填)" clearable />
					<el-text class="mx-1" size="small" type="danger">{{userTip.pwd2Tip}}</el-text>
				</el-form-item>
				<el-form-item prop="user_email">
					<el-input v-model="user.user_email" placeholder="邮箱(选填)" clearable />
					<el-text class="mx-1" size="small" type="danger">{{userTip.pwd2Tip}}</el-text>
				</el-form-item>
				<el-form-item prop="captcha">
					<el-col :span="14">
						<el-input v-model="user.captcha" placeholder="请输入验证码" clearable></el-input>
						<el-text class="mx-1" size="small" type="danger">{{userTip.captchaTip}}</el-text>
					</el-col>
					<el-col :span="1">
						&nbsp;
					</el-col>
					<el-col :span="9">
						<img :src="yzmUrl" alt="验证码" @click="refreshYzm"
							style="width: 120px; height: 100%; opacity: 0.5;" />
					</el-col>
				</el-form-item>
				<el-button type="primary" style="margin-left:10px;width: 320px;height: 40px;"
					@click="doRegister()">注册</el-button>

				<p>
					&nbsp;
					<a href="#" id="left">手机短信登录</a>
					<span id="right">
						<a href="register">注册</a> |

						<a href="ShouYeIndex">首页</a>
					</span>
				</p>

			</el-form>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="goBack">关闭</el-button>
				<el-button @click="doFormReset">重置</el-button>
				<!-- <el-button type="primary" @click="doLogin">登录</el-button> -->
			</div>
		</template>
	</el-dialog>
</template>
<script lang="ts" setup>
	import { nextTick, ref } from 'vue'
	import axios from 'axios';
	import { ElMessage, FormInstance } from 'element-plus'
	const user = ref({
		user_name: '',
		pwd: '',
		pwd2: '',
		captcha: '',
		user_pwd: '',
		user_sjh: '',
		user_email: '',
	});
	const userTip = ref({
		yhmTip: '',
		pwdTip: '',
		pwd2Tip: '',
		captchaTip: ''
	})
	const yzmUrl = ref('')
	const userRef = ref<FormInstance>()
	const goBack = () => {
		window.location.href = "shouYeIndex";
	}


	const checkUsername = () => {
		if (user.value.user_name.length == 0 || /^\s+$/.test(user.value.user_name)) {
			userTip.value.yhmTip = '请输入用户名'
			// alert('请输入用户名')
			return false;
		} else {
			if (/^\d{10,}$/.test(user.value.user_name)) {
				userTip.value.yhmTip = '不能为纯数字'
				return false;
			} else {
				if (/[@#$%^&*()-_+=\{\}\|'";:<>.,?\/]/.test(user.value.user_name)) {
					userTip.value.yhmTip = '含有特殊字符'
					return false;
				} else {
					userTip.value.yhmTip = ''
					return axios({
						url: "/api/user/" + user.value.user_name,
						method: "get",
						// params:{yhm:this.user.yhm}
					}).then((response) => {
						console.log("用户名：" + response.data)
						if (response.data == false) {
							userTip.value.yhmTip = ''
							return true;// 设置用户名有效
						} else {
							userTip.value.yhmTip = '用户名已被注册'
							// alert('用户名已被注册')
							return false; // 设置提示信息为“用户名已被注册！”
						}
					});
				}

			}

		}
	}
	const checkPwd = () => {
		if (/^\d{6,10}$/.test(user.value.pwd) == false) {
			userTip.value.pwdTip = '密码非法'
			// alert('密码非法')
			return false
		} else {
			userTip.value.pwdTip = ''
			return true
		}
	}
	const checkPwd2 = () => {
		if (user.value.pwd != user.value.pwd2) {
			userTip.value.pwd2Tip = '两次输入的密码不一致'
			// alert('两次输入的密码不一致')
			return false
		} else {
			userTip.value.pwd2Tip = ''
			return true
		}
	}
	//刷新验证码
	const refreshYzm = () => {
		axios.get('/api/user/yzm2').then((response) => {
			// console.log(response.data)
			yzmUrl.value = '/api/src/directory/' + response.data;
		});
	}

	//检查验证码
	// const checkCaptcha = () => {
	// 	if (user.value.captcha.length == 0 || /^\s+$/.test(user.value.captcha)) {
	// 		userTip.value.captchaTip = '请输入验证码'
	// 		// alert('请输入验证码')
	// 		return false
	// 	} else {
	// 		userTip.value.captchaTip = ''
	// 		axios({
	// 			url: '/api/user/yzm2/' + user.value.captcha,
	// 			method: 'get'
	// 		}).then((response) => {
	// 			console.log("验证码：" + response.data)
	// 			if (response.data == true) {
	// 				userTip.value.captchaTip = ''
	// 				return true
	// 			} else {
	// 				userTip.value.captchaTip = '验证码错误'
	// 				// alert('验证码错误')
	// 				return false
	// 			}
	// 		})
	// 	}
	// }

	const checkCaptcha = async () => {
		if (user.value.captcha.length === 0 || /^\s+$/.test(user.value.captcha)) {
			userTip.value.captchaTip = '请输入验证码';
			return false;
		} else {
			try {
				const response = await axios({
					url: '/api/user/yzm2/' + user.value.captcha,
					method: 'get'
				});
				console.log('验证码验证响应：', response);
				if (response.data === true) {
					userTip.value.captchaTip = '';
					return true;
				} else {
					userTip.value.captchaTip = '验证码错误';
					return false;
				}
			} catch (error) {
				console.error('验证码验证错误：', error);
				return false;
			}
		}
	};
	const doRegister = async () => {

		const [usernameValid, passwordValid, captchaValid, password2Valid] = await Promise.all([
			checkUsername(),
			checkPwd(),
			checkPwd2(),
			checkCaptcha()
		]);
		if (usernameValid && passwordValid && password2Valid && captchaValid) {
			user.value.user_pwd = user.value.pwd;
			axios({
				url: '/api/user',
				method: 'post',
				params: user.value
			}).then((response) => {
				console.log("注册状态：" + response.data)
				//注册成功跳转到登录界面，注册失败回到注册界面
				if (response.data == true) {
					ElMessage.success("注册成功！");
					window.location.href = "http://localhost:3000/pagesIndex/login";
				} else {
					ElMessage.success("注册失败！");
					window.location.href = "http://localhost:3000/pagesIndex/shouYeIndex"
				}
			})
		}
	}
	const dialogFormVisible = ref(false)

	const handleRegisterForm = () => {

		dialogFormVisible.value = true;
		nextTick(() => {
			axios.get('/api/user/yzm2').then((response) => {
				console.log("yzm:" + response)
				yzmUrl.value = '/api/src/directory/' + response.data;
			});

		})
		doFormReset();
	}

	const doFormReset = () => {
		// 重置表单字段 
		if (userRef.value) {
			userRef.value.resetFields();
			userTip.value.yhmTip = '';
			userTip.value.pwdTip = '';
			userTip.value.pwd2Tip = '';
			userTip.value.captchaTip = '';
		}
	};


	// const cancelForm = () => {
	// 	dialogFormVisible.value = false;
	// 	doFormReset();
	// };
	// 将handleAddForm暴露给父组件
	defineExpose({
		handleRegisterForm
	})
</script>
<style>
	.login-containers {
		width: 400px;
		height: 500px;
		display: flex;
		justify-content: center;
		align-items: center;
		padding-right: 20px;
		padding-top: 20px;
		margin-top: 20px;
		background-image: url(./adminPage/musicMgr/img.png);
		background-size: cover;
		/* 确保背景图片覆盖整个容器 */
		background-position: center;
		/* 确保背景图片居中 */
		background-repeat: no-repeat;
		/* 防止背景图片重复 */
	}

	,
	.login-forms {
		width: 400px;
		padding: 20px;
		background-color: #fff;
		border-radius: 5px;
		box-shadow: 0 1px 3px rgba(0, 0, 0, .1);
	}

	.error-text {
		display: block;
		margin-top: 5px;
		color: red;
	}
</style>